package org.dejlis.kurzycnb;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;

import android.widget.Spinner;
import android.widget.TextView;

public class DisplayRatesActivity 
	extends Activity 
	implements OnItemSelectedListener{
	String resultStringCNB;
	TextView textView;
	Spinner spinner;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// initialization
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_display_rates);
		
		// Set the text view 
		textView = (TextView) findViewById(R.id.resultView);		
		// Show the Up button in the action bar.
		setupActionBar();

		// Currency spinner
		spinner = (Spinner) findViewById(R.id.spinnerCurrency);
		spinner.setOnItemSelectedListener(this);
		// Get the message from the intent
		Intent intent = getIntent();
		String url = intent.getStringExtra(MainActivity.EXTRA_URL);
		// Fetch the data
		fetchRatesURL(url);
		
		//hmmm
		textView.setText(resultStringCNB);			

	}
	protected void onResume(Bundle savedInstanceState){
		textView.setText(resultStringCNB);
	}

	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.display_rates, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void fetchRatesURL(String url) {
		// Fetch the rates from pre-defined CNB url
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {        
			// fetch data
			DownloadWebpageTask downloadTask = new DownloadWebpageTask(); 
			downloadTask.execute(url);
		} else {        
			// TODO: display error
			
		}	
	}	
	
	public class DownloadWebpageTask extends AsyncTask<String, Void, String> {
		private static final String DEBUG_TAG = "HTTP Response";		
		
		@Override
		protected String doInBackground(String... urls) {
	        // params comes from the execute() call: params[0] is the url.            
			try {                
				return downloadUrl(urls[0]);            
			} catch (IOException e) 
			{                
				return "Unable to retrieve web page. URL may be invalid.";            
			}
		}

		private String downloadUrl(String myurl) throws IOException {
			// Given a URL, establishes an HttpUrlConnection and retrieves
			// the web page content as a InputStream, which it returns as string
			InputStream is = null;
			try {
				URL url = new URL(myurl);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setReadTimeout(10000 /* milliseconds */);
				conn.setConnectTimeout(15000 /* milliseconds */);
				conn.setRequestMethod("GET");
				conn.setDoInput(true);
				// Starts the query
				conn.connect();
				int response = conn.getResponseCode();
				Log.d(DEBUG_TAG, "The response is: " + response);
				is = conn.getInputStream();
				// Convert the InputStream into a string
				String contentAsString = readIt(is);
				return contentAsString;
			} finally {
				if (is != null) {
					is.close();
				}
			}		
		}

		private String readIt(InputStream is) {
			String inputStreamString = new Scanner(is,"UTF-8").useDelimiter("\\A").next();
			return inputStreamString;
		}

		protected void onPostExecute(String result) {
			System.out.println("Download finished. Triggering event.");
			resultStringCNB = result;
			setCurrencySpinner(result);
			textView.setText(resultStringCNB);

		}

		private void setCurrencySpinner(String result) {
			List<String> list = new ArrayList<String>();
			String[] lines = result.split("\n");
			for(int i = 0; i<= lines.length; i++){
				String[] columns = lines[i].split("|");
				list.add(columns[0]);
			}
			ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(DisplayRatesActivity.this, android.R.layout.simple_spinner_item, list);				
			dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner.setAdapter(dataAdapter);		
		}
		
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// An item was selected. You can retrieve the selected item using
		// parent.getItemAtPosition(pos)
		
	}
	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// Another interface callback
		
	}	
	
}
